//获取富文本内的图片url地址
export function getImgSrc(richtext, num = 3) {
	let imgList = [];
	richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
		imgList.push(capture);
	});
	imgList = imgList.slice(0, num)
	return imgList;
}

//向外导出省份
export function getProvince() {
	return new Promise((resolve, reject) => {
		let historyProvince = uni.getStorageSync("historyProvince");
		// 如果本地有缓存，直接取缓存，不用再发请求。
		if (historyProvince) {
			if ((Date.now() - historyProvince.time) > 1000 * 60 * 60) {
				getIp().then(res => {
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			} else {
				resolve(historyProvince.province);
			}
		} else {
			getIp().then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		}
	})
}

//获取所在省市
function getIp() {
	return new Promise((resolve, reject) => {
		uni.request({
			// 高德地图api
			url: "https://restapi.amap.com/v3/ip?key=6d3bbd1cb889e22b13baa62e59498aba",
			success: res => {
				console.log(res, "发起了网络请求");
				let str = ""
				typeof(res.data.province) == "string" ? str = res.data.province: str = "火星"; // 如果获取不到地址，就显示火星
				resolve(str)
				let obj = {
					province: str,
					time: Date.now()
				}
				uni.setStorageSync("historyProvince", obj);
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

// 向外导出由生日映射星座的函数
export function getConstellation(date) {
	const month = date.split("-")[1];
	const day = date.split("-")[2];
	return getAstro(month,day);
}
function getAstro(m,d){
   return "魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯".substr(m*2-(d<"102123444543".charAt(m-1)- -19)*2,2);
}

// 计算生日的函数
export function getCalculateMonthAge(birthday) {
    // 假设 birthday 是一个符合 'YYYY-MM-DD' 格式的字符串
    const today = new Date();
    const birthDate = new Date(birthday);
 
    // 计算年份差异
    const yearDiff = today.getFullYear() - birthDate.getFullYear();
 
    // 计算今天是否在生日这一年的后面，如果是，则减去1岁
    const monthDiff = today.getMonth() - birthDate.getMonth();
    const dayDiff = today.getDate() - birthDate.getDate();
    if (dayDiff < 0 || (dayDiff === 0 && monthDiff < 0)) {
        yearDiff--;
    }
 
    // 返回计算出的月龄
    return yearDiff +'岁' + monthDiff + '月';
}

// 计算陪伴你的天数
export function getDaysArrived(arriveTime) {
    const birthDate = new Date(arriveTime);
    const today = new Date();
    const timeDiff = today.getTime() - birthDate.getTime();
	// 截取整数部分
	const days = parseInt(timeDiff / (1000 * 60 * 60 * 24));
	return days;
}